# -*- coding: utf-8 -*-
"""
快捷键设置窗口
用于配置全局快捷键
"""

import tkinter as tk
from tkinter import ttk, messagebox
from pynput import keyboard

# 主题配色
COLORS = {
    'bg_primary': '#0a0a0a',      # 玄青黑
    'bg_secondary': '#1a1a1a',    # 深灰
    'bg_tertiary': '#2a2a2a',     # 中灰
    'accent_gold': '#FFD700',     # 鎏金
    'accent_red': '#E53A3A',      # 血月红
    'text_primary': '#FFFFFF',    # 主文字
    'text_secondary': '#CCCCCC',  # 次要文字
    'text_muted': '#888888',      # 暗淡文字
    'success': '#4CAF50',         # 成功绿
    'warning': '#FF9800',         # 警告橙
    'error': '#F44336'            # 错误红
}


class HotkeySettingsWindow:
    """快捷键设置窗口类"""
    
    def __init__(self, parent, config, callback):
        self.parent = parent
        self.config = config
        self.callback = callback  # 更新快捷键的回调函数
        
        # 创建窗口
        self.window = tk.Toplevel(parent)
        self.window.title("⚙️ 快捷键设置")
        self.window.geometry("550x450")
        self.window.resizable(False, False)
        
        # 设置深色主题
        self.window.configure(bg=COLORS['bg_primary'])
        self.setup_styles()
        
        # 设置为模态窗口
        self.window.transient(parent)
        self.window.grab_set()
        
        # 居中显示
        self.center_window()
        
        # 当前正在设置的按键
        self.current_setting_key = None
        self.key_listener = None
        
        # 快捷键变量
        self.hotkey_vars = {}
        
        # 创建UI
        self.create_widgets()
        self.load_current_settings()
        
        # 绑定关闭事件
        self.window.protocol("WM_DELETE_WINDOW", self.on_closing)
    
    def center_window(self):
        """窗口居中显示"""
        self.window.update_idletasks()
        x = (self.window.winfo_screenwidth() // 2) - (550 // 2)
        y = (self.window.winfo_screenheight() // 2) - (450 // 2)
        self.window.geometry(f"550x450+{x}+{y}")
    
    def setup_styles(self):
        """设置ttk样式主题"""
        style = ttk.Style()
        style.theme_use('clam')
        
        # 配置Frame样式
        style.configure('Dark.TFrame', 
                       background=COLORS['bg_primary'],
                       borderwidth=0)
        
        # 配置LabelFrame样式
        style.configure('Dark.TLabelframe', 
                       background=COLORS['bg_primary'],
                       bordercolor=COLORS['accent_gold'],
                       borderwidth=2,
                       relief='solid')
        style.configure('Dark.TLabelframe.Label',
                       background=COLORS['bg_primary'],
                       foreground=COLORS['accent_gold'],
                       font=('Microsoft YaHei UI', 10, 'bold'))
        
        # 配置Button样式
        style.configure('Gold.TButton',
                       background=COLORS['accent_gold'],
                       foreground=COLORS['bg_primary'],
                       borderwidth=0,
                       focuscolor='none',
                       font=('Microsoft YaHei UI', 9, 'bold'))
        style.map('Gold.TButton',
                 background=[('active', '#FFE55C'),
                           ('pressed', '#E6C200')])
        
        style.configure('Red.TButton',
                       background=COLORS['accent_red'],
                       foreground=COLORS['text_primary'],
                       borderwidth=0,
                       focuscolor='none',
                       font=('Microsoft YaHei UI', 9, 'bold'))
        style.map('Red.TButton',
                 background=[('active', '#FF6B6B'),
                           ('pressed', '#D32F2F')])
        
        style.configure('Dark.TButton',
                       background=COLORS['bg_tertiary'],
                       foreground=COLORS['text_primary'],
                       borderwidth=1,
                       bordercolor=COLORS['accent_gold'],
                       focuscolor='none',
                       font=('Microsoft YaHei UI', 9))
        style.map('Dark.TButton',
                 background=[('active', COLORS['bg_secondary']),
                           ('pressed', COLORS['bg_primary'])])
        
        # 配置Label样式
        style.configure('Title.TLabel',
                       background=COLORS['bg_primary'],
                       foreground=COLORS['accent_gold'],
                       font=('Microsoft YaHei UI', 14, 'bold'))
        
        style.configure('Status.TLabel',
                       background=COLORS['bg_primary'],
                       foreground=COLORS['text_secondary'],
                       font=('Microsoft YaHei UI', 9))
        
        style.configure('Tip.TLabel',
                       background=COLORS['bg_primary'],
                       foreground=COLORS['text_muted'],
                       font=('Microsoft YaHei UI', 8))
        
        style.configure('Key.TLabel',
                       background=COLORS['bg_tertiary'],
                       foreground=COLORS['text_primary'],
                       bordercolor=COLORS['accent_gold'],
                       borderwidth=1,
                       relief='solid',
                       font=('Microsoft YaHei UI', 9, 'bold'))
    
    def create_widgets(self):
        """创建UI组件"""
        # 主框架
        main_frame = ttk.Frame(self.window, padding="20", style='Dark.TFrame')
        main_frame.pack(fill="both", expand=True)
        
        # 标题
        title_label = ttk.Label(main_frame, text="⚙️ 快捷键设置", style='Title.TLabel')
        title_label.pack(pady=(0, 20))
        
        # 说明文字
        info_label = ttk.Label(main_frame, text="点击'设置'按钮后按下想要设置的按键", style='Status.TLabel')
        info_label.pack(pady=(0, 10))
        
        # 快捷键设置区域
        settings_frame = ttk.LabelFrame(main_frame, text="🔑 快捷键配置", padding="15", style='Dark.TLabelframe')
        settings_frame.pack(fill="both", expand=True, pady=(0, 20))
        
        # 快捷键设置项
        hotkey_configs = [
            ('start_recording', '开始录制', 'F9'),
            ('stop_recording', '停止录制', 'F10'),
            ('play_script', '播放脚本', 'F11'),
            ('stop_playing', '停止播放', 'F12'),
            ('emergency_stop', '紧急停止', 'Esc')
        ]
        
        for i, (key, label, default) in enumerate(hotkey_configs):
            # 标签
            ttk.Label(settings_frame, text=f"{label}:", style='Status.TLabel').grid(row=i, column=0, sticky="w", padx=(0, 15), pady=8)
            
            # 显示当前快捷键的标签
            var = tk.StringVar(value=default)
            self.hotkey_vars[key] = var
            key_label = ttk.Label(settings_frame, textvariable=var, style='Key.TLabel', width=15, anchor='center')
            key_label.grid(row=i, column=1, padx=(0, 15), pady=8)
            
            # 设置按钮
            set_btn = ttk.Button(settings_frame, text="⚙️ 设置", style='Gold.TButton',
                               command=lambda k=key: self.start_key_capture(k))
            set_btn.grid(row=i, column=2, padx=(0, 10), pady=8)
            
            # 重置按钮
            reset_btn = ttk.Button(settings_frame, text="🔄 重置", style='Dark.TButton',
                                 command=lambda k=key, d=default: self.reset_key(k, d))
            reset_btn.grid(row=i, column=3, pady=8)
        
        # 状态标签
        self.status_label = ttk.Label(settings_frame, text="💡 点击'设置'按钮后按下想要设置的按键", style='Tip.TLabel')
        self.status_label.grid(row=len(hotkey_configs), column=0, columnspan=4, pady=(15, 0))
        
        # 按钮区域
        button_frame = ttk.Frame(main_frame, style='Dark.TFrame')
        button_frame.pack(fill="x", pady=(20, 0))
        
        # 保存按钮
        save_btn = ttk.Button(button_frame, text="💾 保存设置", style='Gold.TButton', command=self.save_settings)
        save_btn.pack(side="right", padx=(10, 0))
        
        # 取消按钮
        cancel_btn = ttk.Button(button_frame, text="❌ 取消", style='Red.TButton', command=self.on_closing)
        cancel_btn.pack(side="right")
        
        # 恢复默认按钮
        default_btn = ttk.Button(button_frame, text="🔄 恢复默认", style='Dark.TButton', command=self.restore_defaults)
        default_btn.pack(side="left")
    
    def load_current_settings(self):
        """加载当前快捷键设置"""
        hotkeys = self.config.get('hotkeys', {})
        for key, var in self.hotkey_vars.items():
            current_value = hotkeys.get(key, var.get())
            var.set(current_value)
    
    def start_key_capture(self, hotkey_name):
        """开始捕获按键"""
        if self.key_listener:
            self.key_listener.stop()
        
        self.current_setting_key = hotkey_name
        self.status_label.config(text=f"请按下要设置为'{self.get_hotkey_label(hotkey_name)}'的按键...")
        
        # 创建按键监听器
        def on_key_press(key):
            try:
                key_name = self.convert_key_to_name(key)
                if key_name:
                    # 在主线程中更新UI
                    self.window.after(0, self.set_hotkey, hotkey_name, key_name)
                    return False  # 停止监听
            except Exception as e:
                print(f"按键捕获错误: {e}")
        
        self.key_listener = keyboard.Listener(on_press=on_key_press)
        self.key_listener.start()
    
    def convert_key_to_name(self, key):
        """将pynput按键转换为字符串名称"""
        try:
            # 功能键
            if key == keyboard.Key.f1: return 'F1'
            elif key == keyboard.Key.f2: return 'F2'
            elif key == keyboard.Key.f3: return 'F3'
            elif key == keyboard.Key.f4: return 'F4'
            elif key == keyboard.Key.f5: return 'F5'
            elif key == keyboard.Key.f6: return 'F6'
            elif key == keyboard.Key.f7: return 'F7'
            elif key == keyboard.Key.f8: return 'F8'
            elif key == keyboard.Key.f9: return 'F9'
            elif key == keyboard.Key.f10: return 'F10'
            elif key == keyboard.Key.f11: return 'F11'
            elif key == keyboard.Key.f12: return 'F12'
            
            # 特殊键
            elif key == keyboard.Key.esc: return 'Esc'
            elif key == keyboard.Key.space: return 'Space'
            elif key == keyboard.Key.enter: return 'Enter'
            elif key == keyboard.Key.tab: return 'Tab'
            elif key == keyboard.Key.backspace: return 'Backspace'
            elif key == keyboard.Key.delete: return 'Delete'
            elif key == keyboard.Key.home: return 'Home'
            elif key == keyboard.Key.end: return 'End'
            elif key == keyboard.Key.page_up: return 'PageUp'
            elif key == keyboard.Key.page_down: return 'PageDown'
            elif key == keyboard.Key.up: return 'Up'
            elif key == keyboard.Key.down: return 'Down'
            elif key == keyboard.Key.left: return 'Left'
            elif key == keyboard.Key.right: return 'Right'
            
            # 修饰键
            elif key == keyboard.Key.ctrl_l or key == keyboard.Key.ctrl_r: return 'Ctrl'
            elif key == keyboard.Key.alt_l or key == keyboard.Key.alt_r: return 'Alt'
            elif key == keyboard.Key.shift_l or key == keyboard.Key.shift_r: return 'Shift'
            
            # 字符键
            elif hasattr(key, 'char') and key.char:
                return key.char.upper()
            
            return None
        except:
            return None
    
    def set_hotkey(self, hotkey_name, key_name):
        """设置快捷键"""
        if self.key_listener:
            self.key_listener.stop()
            self.key_listener = None
        
        # 检查是否与其他快捷键冲突
        for other_key, var in self.hotkey_vars.items():
            if other_key != hotkey_name and var.get() == key_name:
                messagebox.showwarning("⚠️ 冲突", f"快捷键 '{key_name}' 已被 '{self.get_hotkey_label(other_key)}' 使用")
                self.status_label.config(text="")
                return
        
        # 设置新的快捷键
        self.hotkey_vars[hotkey_name].set(key_name)
        self.status_label.config(text=f"✅ '{self.get_hotkey_label(hotkey_name)}' 已设置为 '{key_name}'")
        self.current_setting_key = None
    
    def reset_key(self, hotkey_name, default_key):
        """重置快捷键为默认值"""
        self.hotkey_vars[hotkey_name].set(default_key)
        self.status_label.config(text=f"🔄 '{self.get_hotkey_label(hotkey_name)}' 已重置为默认值")
    
    def get_hotkey_label(self, hotkey_name):
        """获取快捷键的中文标签"""
        labels = {
            'start_recording': '开始录制',
            'stop_recording': '停止录制',
            'play_script': '播放脚本',
            'stop_playing': '停止播放',
            'emergency_stop': '紧急停止'
        }
        return labels.get(hotkey_name, hotkey_name)
    
    def restore_defaults(self):
        """恢复默认设置"""
        defaults = {
            'start_recording': 'F9',
            'stop_recording': 'F10',
            'play_script': 'F11',
            'stop_playing': 'F12',
            'emergency_stop': 'Esc'
        }
        
        for key, default_value in defaults.items():
            if key in self.hotkey_vars:
                self.hotkey_vars[key].set(default_value)
        
        self.status_label.config(text="🔄 已恢复默认快捷键设置")
    
    def save_settings(self):
        """保存快捷键设置"""
        try:
            # 获取当前设置
            new_hotkeys = {}
            for key, var in self.hotkey_vars.items():
                new_hotkeys[key] = var.get()
            
            # 更新配置
            for key, value in new_hotkeys.items():
                self.config.set(f'hotkeys.{key}', value)
            
            # 保存配置文件
            if self.config.save_config():
                messagebox.showinfo("✅ 成功", "快捷键设置已保存")
                
                # 重新设置快捷键
                if self.callback:
                    self.callback()
                
                self.on_closing()
            else:
                messagebox.showerror("❌ 错误", "保存配置失败")
                
        except Exception as e:
            messagebox.showerror("❌ 错误", f"保存设置失败: {e}")
    
    def on_closing(self):
        """关闭窗口"""
        if self.key_listener:
            self.key_listener.stop()
        
        self.window.grab_release()
        self.window.destroy()